package com.lx.controller;

import com.lx.model.User;
import com.lx.service.AuthService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 段誉
 * @create 2019-06-26 15:13
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
  @Value("${jwt.header}")
  private String tokenHeader;

  @Autowired
  private AuthService authService;

  @PostMapping
  public ResponseEntity<?> createAuthenticationToken(
          @RequestBody User user) {
    final String token = authService.login(user.getUsername(),
            user.getPassword());
    return ResponseEntity.ok(token);
  }

  @GetMapping("/refresh")
  public ResponseEntity<?> refreshAuthenticationToken(HttpServletRequest request) {
    String token = request.getHeader(tokenHeader);
    String refreshedToken = authService.refresh(token);
    if (refreshedToken == null) {
      return ResponseEntity.badRequest().body(null);
    }
    return ResponseEntity.ok(refreshedToken);
  }

  @PostMapping("/register")
  public User register(@RequestBody User user) {
    return authService.register(user);
  }
}
